# -*- coding: utf8 -*-
#
# Copyright (c) 2009 Matías Ribecky <mail@mribecky.com.ar>
#
# This file is part of twitter-notifications.
# 
# twitter-notifications is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# twitter-notifications is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License along
# with twitter-notifications.  If not, see <http://www.gnu.org/licenses/>.

'''Manages the configuration.'''

import os
import logging
import ConfigParser

import xdg.BaseDirectory

LOGGER = logging.getLogger('twitternotifications.config')

def load():
    '''Loads the config.

    :return: A dict with the keys username and password
    '''

    LOGGER.info('Reading configuration files')

    cfg_parser = ConfigParser.ConfigParser()
    cfg_parser.add_section('user')
    cfg_parser.add_section('notifier')
    cfg_parser.read(_config_paths())

    cfg = {}
    if cfg_parser.has_option('user', 'username'):
        cfg['username'] = cfg_parser.get('user', 'username')
    else:
        cfg['username'] = None
    if cfg_parser.has_option('user', 'password'):
        cfg['password'] = cfg_parser.get('user', 'password')
    else:
        cfg['password'] = None

    if cfg_parser.has_option('notifier', 'times'):
        cfg['times'] = cfg_parser.get('notifier', 'times')
    else:
        cfg['times'] = 1
    if cfg_parser.has_option('notifier', 'timeout'):
        cfg['timeout'] = cfg_parser.get('notifier', 'timeout')
    else:
        cfg['timeout'] = 10

    return cfg

def _config_paths():
    '''Returns a lis of the config files to read.'''
    paths = xdg.BaseDirectory.load_config_paths('twitter-notifications')
    paths = [os.path.join(path, 'user.cfg') for path in paths]
    paths = [path for path in paths if os.path.exists(path)]
    return paths
